<template>
  <div
    style="display: flex; width: 100%; justify-content: space-around"
    v-loading="log"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <Card style="width: 40%; height: 70vh">
      <template #title>组织列表</template>
      <el-input placeholder="输入关键字进行过滤" v-model="filterText">
      </el-input>
      <el-tree
        style="margin-top: 20px"
        @node-click="handleNodeClick"
        accordion
        :filter-node-method="filterNode"
        :data="menus"
        node-key="id"
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button
              type="text"
              icon="el-icon-circle-plus-outline"
              size="mini"
              @click="() => append(data)"
            >
              新增
            </el-button>
            <el-button
              type="text"
              icon="el-icon-circle-close"
              size="mini"
              @click="() => remove(node, data)"
            >
              删除
            </el-button>
            <el-button
              type="text"
              icon="el-icon-edit"
              size="mini"
              @click="() => edit(node, data)"
            >
              编辑
            </el-button>
          </span>
        </span>
      </el-tree>
    </Card>
    <Card style="width: 60%; height: 70vh">
      <template #title
        >员工信息 {{ nodeName == "" ? "" : " / " + nodeName }}</template
      >
      <el-table
        :data="organizationData"
        style="width: 100%"
        max-height="440"
        ref="multipleTable"
      >
        <el-table-column fixed="left" prop="code" label="序号" width="50">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="left" prop="name" label="员工姓名" width="120">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="140">
        </el-table-column>
        <el-table-column prop="createTime" label="所属机构" width="180">
          <template>
            <span>{{ nodeName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="系统账号" width="140">
        </el-table-column>
        <el-table-column label="账号状态" width="140">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == true ? 'success' : 'info'">{{
              scope.row.status == true ? "启用" : "禁用"
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="180">
          <div>
            <el-link type="primary">编辑</el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link type="primary">删除</el-link>
          </div>
        </el-table-column>
      </el-table>
    </Card>

    <!-- 新增 -->
    <Modal
      v-model="modalAdd"
      draggable
      sticky
      scrollable
      :mask="false"
      title="新增组织信息"
      :width="700"
    >
      <div>
        <Form ref="organization" :model="organization" :label-width="80">
          <FormItem label="机构名称">
            <Input v-model="organization.name" placeholder="机构名称"></Input>
          </FormItem>
          <FormItem label="父级机构名称">
            <Input v-model="nodeName" placeholder="机构名称" disabled></Input>
          </FormItem>
          <FormItem label="机构地址">
            <el-cascader
              v-model="value"
              :options="areaoptions"
              @change="handleChange"
              clearable
            ></el-cascader>
          </FormItem>
          <FormItem label="详细地址">
            <Input
              style="margin-top: 10px"
              v-model="organization.address"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入详细地址"
            ></Input>
          </FormItem>
          <FormItem label="状态" prop="status">
            <RadioGroup v-model="organization.status">
              <Radio :label="1" border>启用</Radio>
              <Radio :label="0" border>禁用</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="所属网点">
            <el-button
              type="success"
              icon="el-icon-map-location"
              circle
              @click="modalEditOrg = true"
            ></el-button>
          </FormItem>
        </Form>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button @click="modalAdd = false">取消</Button>
        <Button type="primary" @click="addOrganization">确认</Button>
      </template>
    </Modal>

    <!-- 编辑 -->
    <Modal
      v-model="modalEdit"
      draggable
      sticky
      scrollable
      :mask="false"
      title="编辑组织信息"
      :width="700"
    >
      <div>
        <Form ref="organization" :model="organizationEdit" :label-width="80">
          <FormItem label="机构名称">
            <Input
              v-model="organizationEdit.name"
              placeholder="机构名称"
            ></Input>
          </FormItem>
          <FormItem label="机构地址">
            <el-cascader
              v-model="value"
              :options="areaoptions"
              @change="handleChange"
              clearable
            ></el-cascader>
          </FormItem>
          <FormItem label="详细地址">
            <Input
              style="margin-top: 10px"
              v-model="organizationEdit.address"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入详细地址"
            ></Input>
          </FormItem>
          <FormItem label="状态" prop="status">
            <RadioGroup v-model="organizationEdit.status">
              <Radio :label="1" border>启用</Radio>
              <Radio :label="0" border>禁用</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="所属网点">
            <el-button
              type="success"
              icon="el-icon-map-location"
              circle
              @click="modalEditOrg = true"
            ></el-button>
          </FormItem>
        </Form>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button @click="modalEdit = false">取消</Button>
        <Button type="primary" @click="updateOrganization">确认</Button>
      </template>
    </Modal>

    <Modal
      v-model="modalEditOrg"
      draggable
      sticky
      scrollable
      :mask="false"
      title="所属网点"
      :width="800"
    >
      <div>
        <!--      搜索组件-->
        <div>
          搜索：
          <el-select
            v-model="keywords"
            filterable
            remote
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading"
            :clearable="true"
            size="mini"
            @change="currentSelect"
            style="width: 500px"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item"
              class="one-text"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.district
              }}</span>
            </el-option>
          </el-select>
        </div>
        <!--      地图组件-->
        <div id="guide-map" style="height: 400px"></div>
      </div>
    </Modal>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: "ea4798fdb3262a50b2c2af3fc321b49b",
};
let id = 1000;

export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.initMap();
  },
  data() {
    return {
      log: true,
      value: [],
      areaoptions: [],
      data: {}, //初始化数据
      organizationData: [], //员工数据
      organization: {
        id: 0, //编号
        name: "", //网点名称
        parentId: "", //父级id
        provinceId: "", //省
        cityId: "", //市
        countyId: "", //区
        address: "", //地址
        status: 1, //状态
        latitude: "", //纬度
        longitude: "", //经度
        createTime: "", //创建时间
        createUser: "", //创建用户
      },
      organizationEdit: {
        id: 0, //编号
        name: "", //网点名称
        parentId: "", //父级id
        provinceId: "", //省
        cityId: "", //市
        countyId: "", //区
        address: "", //地址
        status: 1, //状态
        latitude: "", //纬度
        longitude: "", //经度
        updateTime: "", //修改时间
        updateUser: "", //修改用户
      },
      modalAdd: false, //新增模态框
      modalEdit: false, //编辑模态框
      modalEditOrg: false, //地图模态框
      menus: [],
      filterText: "",
      nodeName: "", //所属网点名称
      token: JSON.parse(sessionStorage.getItem("satoken")), //登入用户信息

      //地图
      //提交表单
      form: {},
      //地图实例
      map: null,
      //路径坐标点集合
      coordinateList: [],
      //起点坐标
      startCoordinate: {},
      //终点坐标
      endCoordinate: {},
      //起点坐标描述
      startCoordinateDescription: "经度：请选择起点" + ",     纬度：请选择起点",
      //终点坐标描述
      endCoordinateDescription: "经度：请选择终点" + ",     纬度：请选择终点",
      //选择起点
      isStart: true,
      //起点Marker
      startMarker: null,
      //终点Marker
      endMarker: null,
      //搜索点Marker
      searchMarker: null,
      // 搜索提示
      AutoComplete: null,
      // 搜索关键字
      keywords: "",
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      //中心点
      center: [],
    };
  },
  created() {
    this.findCoreOrgUser();
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /**
     * 打开新增模态框
     * @param {*} data
     */
    append(data) {
      this.value = [];
      this.organization = {
        id: 0, //编号
        name: "", //网点名称
        parentId: "", //父级id
        provinceId: "", //省
        cityId: "", //市
        countyId: "", //区
        address: "", //地址
        status: 1, //状态
        latitude: "", //纬度
        longitude: "", //经度
        createTime: "", //创建时间
        createUser: "", //创建用户
      };
      this.organization.parentId = data.id;
      const eventObj = {
        lnglat: new AMap.LngLat(0, 0), // 创建一个具有经纬度信息的LngLat对象
      };
      this.clickMapHandler(eventObj);
      this.modalAdd = true;
    },
    addOrganization() {
      if (this.organization.name == "") {
        this.$Message.error("请输入组织名称");
        return;
      }
      if (this.value.length <= 0) {
        this.$Message.error("请选择机构地址");
        return;
      }
      if (
        this.organization.longitude == "" &&
        this.organization.latitude == ""
      ) {
        this.$Message.error("请选择所属网点");
        return;
      }
      var now = new Date();
      var month = (now.getMonth() + 1).toString().padStart(2, "0");
      var day = now.getDate().toString().padStart(2, "0");
      this.organization.provinceId = this.value[0];
      this.organization.cityId = this.value[1];
      this.organization.countyId = this.value[2];
      this.organization.createUser = this.token.loginId;
      this.organization.createTime =
        now.getFullYear() +
        "-" +
        month +
        "-" +
        day +
        " " +
        now.getHours() +
        ":" +
        now.getMinutes() +
        ":" +
        now.getSeconds();
      this.axios
        .post("/api/auth/pd_core_org/addOrganization", this.organization)
        .then((r) => {
          if (r.data.code == 11051) {
            this.$Message.error(r.data.msg);
          }
          if (r.data.code == 200) {
            this.findCoreOrgUser();
            this.modalAdd = false;
            this.$Message.success("成功新增一条数据!");
          }
        });
    },

    remove(node, data) {
      this.$confirm("此操作将永久删除该组织, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .post("/api/auth/pd_core_org/removeOrganization/" + data.id)
            .then((r) => {
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.data == true) {
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex((d) => d.id === data.id);
                children.splice(index, 1);
                this.$Message.success("成功删除一条数据");
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    findCoreOrgUser() {
      try {
        this.axios.post("/api/auth/pd_core_org/findCoreOrgUser").then((r) => {
          if (r.data.code == 11051) {
            this.log = false;
            this.$Message.error(r.data.msg);
          }
          if (r.data.code == 200) {
            this.data = r.data.data;
            let menus = [];
            r.data.data.organization.forEach((m1) => {
              if (m1.parentId == 0) {
                var m1 = {
                  id: m1.id,
                  label: m1.name,
                  status: m1.status,
                  provinceId: m1.provinceId, //省id
                  cityId: m1.cityId, //市id
                  countyId: m1.countyId, //区id
                  latitude: m1.latitude, //纬度
                  longitude: m1.longitude, //经度
                  address: m1.address, //详细地址
                  children: [],
                };
                r.data.data.organization.forEach((m2) => {
                  if (m1.id == m2.parentId) {
                    var m2 = {
                      id: m2.id,
                      label: m2.name,
                      status: m2.status,
                      provinceId: m2.provinceId, //省id
                      cityId: m2.cityId, //市id
                      countyId: m2.countyId, //区id
                      latitude: m2.latitude, //纬度
                      longitude: m2.longitude, //经度
                      address: m2.address, //详细地址
                      children: [],
                    };
                    m1.children.push(m2);
                    r.data.data.organization.forEach((m3) => {
                      if (m2.id == m3.parentId) {
                        var m3 = {
                          id: m3.id,
                          label: m3.name,
                          provinceId: m3.provinceId, //省id
                          cityId: m3.cityId, //市id
                          countyId: m3.countyId, //区id
                          latitude: m3.latitude, //纬度
                          longitude: m3.longitude, //经度
                          address: m3.address, //详细地址
                          children: [],
                        };
                        m2.children.push(m3);
                        r.data.data.organization.forEach((m4) => {
                          if (m3.id == m4.parentId) {
                            var m4 = {
                              id: m4.id,
                              label: m4.name,
                              provinceId: m4.provinceId, //省id
                              cityId: m4.cityId, //市id
                              countyId: m4.countyId, //区id
                              latitude: m4.latitude, //纬度
                              longitude: m4.longitude, //经度
                              address: m4.address, //详细地址
                              children: [],
                            };
                            m3.children.push(m4);
                            r.data.data.organization.forEach((m5) => {
                              if (m4.id == m5.parentId) {
                                var m5 = {
                                  id: m5.id,
                                  label: m5.name,
                                  provinceId: m5.provinceId, //省id
                                  cityId: m5.cityId, //市id
                                  countyId: m5.countyId, //区id
                                  latitude: m5.latitude, //纬度
                                  longitude: m5.longitude, //经度
                                  address: m5.address, //详细地址
                                  children: [],
                                };
                                m4.children.push(m5);
                              }
                            });
                          }
                        });
                      }
                    });
                  }
                });
                menus.push(m1);
              }
            });
            let areas = [];
            r.data.data.areas.forEach((a1) => {
              if (a1.pid == 0) {
                var areas1 = {
                  value: a1.id,
                  label: a1.name,
                  children: [],
                };
                r.data.data.areas.forEach((a2) => {
                  if (a1.id == a2.pid) {
                    var areas2 = {
                      value: a2.id,
                      label: a2.name,
                      children: [],
                    };
                    areas1.children.push(areas2);
                    r.data.data.areas.forEach((a3) => {
                      if (a2.id == a3.pid) {
                        var areas3 = {
                          value: a3.id,
                          label: a3.name,
                        };
                        areas2.children.push(areas3);
                      }
                    });
                  }
                });
                areas.push(areas1);
              }
            });
            this.areaoptions = areas;
            this.menus = menus;
            this.log = false;
          }
        });
      } catch (error) {}
    },
    handleNodeClick(node) {
      this.nodeName = node.label;
      this.organizationData = [];
      this.data.users.forEach((r) => {
        if (r.orgId == node.id) {
          this.organizationData.push(r);
        }
      });
    },
    /**
     * 打开编辑组织模态框
     */
    edit(node, data) {
      console.log(node, data);
      this.organizationEdit.id = data.id; //编号
      this.organizationEdit.name = data.label; //编号
      this.value = [data.provinceId, data.cityId, data.countyId]; //地区
      this.organizationEdit.address = data.address; //详细地址
      this.organization.status = data.status; //状态
      this.organizationEdit.longitude = data.longitude; //经度
      this.organizationEdit.latitude = data.latitude; //经度
      console.log(data.longitude != "");
      if (data.longitude != null && data.latitude != null) {
        this.map.setCenter([data.longitude, data.latitude]); // 确保地图的中心点已被正确更新
        const eventObj = {
          lnglat: new AMap.LngLat(data.longitude, data.latitude), // 创建一个具有经纬度信息的LngLat对象
        };
        this.clickMapHandler(eventObj);
      }
      this.modalEdit = true;
    },
    /**
     * 编辑组织信息
     * @param {*} name
     */
    updateOrganization() {
      try {
        var now = new Date();
        var month = (now.getMonth() + 1).toString().padStart(2, "0");
        var day = now.getDate().toString().padStart(2, "0");
        this.organizationEdit.provinceId = this.value[0];
        this.organizationEdit.cityId = this.value[1];
        this.organizationEdit.countyId = this.value[2];
        this.organizationEdit.updateUser = this.token.loginId;
        this.organizationEdit.updateTime =
          now.getFullYear() +
          "-" +
          month +
          "-" +
          day +
          " " +
          now.getHours() +
          ":" +
          now.getMinutes() +
          ":" +
          now.getSeconds();

        this.axios
          .post(
            "/api/auth/pd_core_org/updateOrganization",
            this.organizationEdit
          )
          .then((r) => {
            if (r.data.code == 11051) {
              this.$Message.error(r.data.msg);
            }
            if (r.data.code == 200) {
              this.findCoreOrgUser();
              this.modalEdit = false;
              this.$Message.success("成功编辑一条数据!");
            }
          });
      } catch (error) {}
    },

    //地图
    //初始化地图
    initMap() {
      AMapLoader.reset();
      AMapLoader.load({
        key: "fd265f602a8a72eeb9449a827c5d7273",
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Marker"], // 需要使用的的插件列表
        AMapUI: {
          version: "1.1",
          plugins: [],
        },
      })
        .then((AMap) => {
          // 初始化地图
          this.map = new AMap.Map("guide-map", {
            viewMode: "2D", //  是否为3D地图模式
            zoom: 13, // 初始化地图级别
            center: [112.915698, 28.237256], //中心点坐标  广州
            resizeEnable: true,
            willreadoften: true,
          });
          //鼠标点击事件
          this.map.on("click", this.clickMapHandler);
          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({ city: "全国" });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 点击地图事件
    clickMapHandler(e) {
      // 清除地图上的所有标点数据
      this.map.clearMap();
      console.log(this.map);
      //选择起点
      if (this.isStart) {
        if (this.startMarker !== null) {
          this.map.remove(this.startMarker);
        }
        this.startCoordinate.lon = e.lnglat.getLng();
        this.startCoordinate.lat = e.lnglat.getLat();
        this.startCoordinateDescription =
          "经度：" +
          this.startCoordinate.lon +
          ",     纬度：" +
          this.startCoordinate.lat;
        this.organization.longitude = e.lnglat.getLng(); //经度 新增
        this.organization.latitude = e.lnglat.getLat(); //纬度  新增
        this.organizationEdit.longitude = e.lnglat.getLng(); //经度 新增
        this.organizationEdit.latitude = e.lnglat.getLat(); //纬度  新增
        //标点
        this.startMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title:
            this.organization.name == ""
              ? this.organizationEdit.name
              : this.organization.name,
          label: {
            content:
              this.organization.name == ""
                ? this.organizationEdit.name
                : this.organization.name,
          },
        });
        // 将创建的点标记添加到已有的地图实例
        this.map.add(this.startMarker);
        console.log(this.data.organization);
        this.data.organization.forEach((o) => {
          console.log(o.name);

          if (o.longitude != null && o.latitude != null) {
            if (
              o.longitude != e.lnglat.getLng() &&
              o.latitude != e.lnglat.getLat()
            ) {
              this.map.add(
                new AMap.Marker({
                  position: new AMap.LngLat(o.longitude, o.latitude), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                  title: o.name,
                  label: {
                    content: o.name,
                  },
                })
              );
            }
          }
        });
      }
      //选择终点
      else {
        if (this.endMarker !== null) {
          this.map.remove(this.endMarker);
        }
        this.endCoordinate.lon = e.lnglat.getLng();
        this.endCoordinate.lat = e.lnglat.getLat();
        this.endCoordinateDescription =
          "经度：" +
          this.endCoordinate.lon +
          ",     纬度：" +
          this.endCoordinate.lat;

        this.endMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: "终点",
          label: {
            content: "终点",
          },
        });
        this.map.add(this.endMarker);
      }
    },
    // 搜索地址
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(query, (status, result) => {
            this.options = result.tips;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 选中提示
    currentSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      //清除marker
      if (this.searchMarker) {
        this.map.remove(this.searchMarker);
      }
      //设置marker
      this.searchMarker = new AMap.Marker({
        map: this.map,
        position: [val.location.lng, val.location.lat],
      });

      this.keywords = val.name;
      //定位
      this.map.setCenter([val.location.lng, val.location.lat]);
    },
  },
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
